#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Nacos 服务发现 Python 示例

安装依赖:
pip install nacos-sdk-python
"""

import nacos
import time

# Nacos 服务器地址
SERVER_ADDRESSES = "localhost:8848"
NAMESPACE = "public"

# 服务信息
SERVICE_NAME = "python-example-service"
IP = "127.0.0.1"
PORT = 8080


def subscribe_callback(event):
    """服务变更回调函数"""
    print(f"\n服务实例变更:")
    for instance in event['instances']:
        print(f"  - {instance['ip']}:{instance['port']} "
              f"(健康: {instance['healthy']}, 权重: {instance['weight']})")


def main():
    # 1. 创建客户端
    client = nacos.NacosClient(
        SERVER_ADDRESSES,
        namespace=NAMESPACE,
        # 如果需要认证
        # username="nacos",
        # password="nacos"
    )
    
    # 2. 注册服务实例
    result = client.add_naming_instance(
        SERVICE_NAME,
        IP,
        PORT,
        cluster_name="DEFAULT",
        weight=1.0,
        metadata={"version": "1.0.0", "env": "dev"},
        enable=True,
        healthy=True,
        ephemeral=True  # 临时实例
    )
    print(f"注册服务: {'成功' if result else '失败'}")
    
    # 3. 查询服务实例
    instances = client.list_naming_instance(SERVICE_NAME)
    print(f"\n服务实例列表:")
    for instance in instances['hosts']:
        print(f"  - {instance['ip']}:{instance['port']} "
              f"(健康: {instance['healthy']}, 权重: {instance['weight']})")
    
    # 4. 选择一个健康实例
    instance = client.select_one_healthy_instance(SERVICE_NAME)
    print(f"\n选择的健康实例: {instance['ip']}:{instance['port']}")
    
    # 5. 订阅服务变更
    client.subscribe(SERVICE_NAME, subscribe_callback)
    print(f"\n已订阅服务变更通知")
    
    # 6. 发送心跳（保持服务在线）
    print(f"\n发送心跳中... (按 Ctrl+C 退出)")
    try:
        count = 0
        while True:
            # 每5秒发送一次心跳
            client.send_heartbeat(SERVICE_NAME, IP, PORT)
            count += 1
            if count % 5 == 0:
                print(f"已发送 {count} 次心跳")
            time.sleep(5)
    except KeyboardInterrupt:
        print("\n正在注销服务...")
        # 7. 注销服务
        client.remove_naming_instance(SERVICE_NAME, IP, PORT)
        print("服务已注销")


if __name__ == "__main__":
    main()

